package com.robert.custombehavior.behavior

import android.content.Context
import android.graphics.Rect
import android.support.design.widget.CoordinatorLayout
import android.support.v4.view.ViewCompat
import android.support.v7.widget.RecyclerView
import android.util.AttributeSet
import android.util.Log
import android.view.View

class HeaderScrollBehavior : CoordinatorLayout.Behavior<View> {

    private val mHeadRect = Rect()

    constructor() {}

    constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {}

    override fun onStartNestedScroll(coordinatorLayout: CoordinatorLayout, child: View, directTargetChild: View, target: View, nestedScrollAxes: Int): Boolean {
        return nestedScrollAxes and ViewCompat.SCROLL_AXIS_VERTICAL != 0
    }

    override fun onNestedPreScroll(coordinatorLayout: CoordinatorLayout, child: View, target: View, dx: Int, dy: Int, consumed: IntArray) {
        if (target is RecyclerView) {
            val down = target.canScrollVertically(1)//向上推
            val up = target.canScrollVertically(-1)//向下拉
            Log.e(TAG, "方向==>$down:$up:$dy")
            val maxTranslationY = getMaxTranslationY(child)
            Log.e(TAG, "当前偏移==>" + child.translationY + "MAX==>" + maxTranslationY)
            if (dy > 0) {//底部
                if (Math.abs(child.translationY - dy) < maxTranslationY) {
                    child.translationY = child.translationY - dy
                } else {
                    child.translationY = (-maxTranslationY).toFloat()
                }
            }
            if (!up && dy < 0) {//顶部
                val translationY = child.translationY
                if (translationY - dy <= 0) {
                    child.translationY = translationY - dy
                } else {
                    child.translationY = 0f
                }
            }
        }
    }

    private fun getMaxTranslationY(view: View): Int {
        return view.measuredHeight
    }

    companion object {

        private val TAG = "HeaderScrollBehavior"
    }
}